package com.cs342.uwosh.cloudycontacts.tasks.network;

import java.io.InputStream;
import java.sql.Date;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import com.cs342.uwosh.cloudycontacts.Category;
import com.cs342.uwosh.cloudycontacts.Contact;
import com.cs342.uwosh.cloudycontacts.MainActivity;
import com.cs342.uwosh.cloudycontacts.RestClient;
import com.cs342.uwosh.cloudycontacts.SqlConnect;
import com.cs342.uwosh.cloudycontacts.tasks.db.AddContactTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.CreateCategoryTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetAllCategoryNamesTask;
import com.cs342.uwosh.cloudycontacts.tasks.db.GetAllContactTask;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import android.graphics.Typeface;
import android.os.AsyncTask;
import android.util.Log;

public class PostToCloudTask extends AsyncTask<Object, Object, Object>
{
	
	public int iLanguage = 0;
	Typeface arabicFont = null;
	int TIMEOUT_MILLISEC = 10000; // = 10 seconds
	
	
	@Override
	protected Object doInBackground(Object... params) {
		SqlConnect db = MainActivity.db;
		ArrayList<Contact> allContacts = (ArrayList<Contact>)db.getAll();
		
		JsonObject thePost = new JsonObject();
		
		JsonArray contactsArray = new JsonArray();
		
		for(Contact c: allContacts)
		{
			JsonObject aContact = new JsonObject();
			aContact.addProperty("name", c.getName());
			aContact.addProperty("address", c.getAddress());
			aContact.addProperty("cell_number", c.getCellNumber());
			aContact.addProperty("alt_number", c.getAltNumber());
			aContact.addProperty("email", c.getEmail());
			aContact.addProperty("comments", c.getComments());
			aContact.addProperty("category", c.getCategoryID());
			aContact.addProperty("contact_time_stamp", c.getTS());
			contactsArray.add(aContact);
		}
		JsonObject x = new JsonObject();
		int userId = MainActivity.db.getUserId();
		x.addProperty("user_id", ""+userId);
		x.addProperty("password", MainActivity.db.getUser()[1]);
		JsonArray userArray = new JsonArray();
		userArray.add(x);
		System.out.println(x.get("user_id").getAsString());
		thePost.add("user", userArray);
		thePost.add("contacts", contactsArray);
		
		ArrayList<Category> allCategories = (ArrayList<Category>) db.getAllCategories();
		
		JsonArray categoriesArray = new JsonArray();
		for(Category c: allCategories)
		{
			JsonObject aCategory = new JsonObject();
			aCategory.addProperty("cid", c.getCid());
			aCategory.addProperty("category_name", c.getCategoryName());
			System.out.println("TSTSTSTSTSTSTSTTSTSTSTSTSTSTTSTSTST");
			System.out.println(c.getTS()+"aa");
			aCategory.addProperty("category_time_stamp", c.getTS());
			categoriesArray.add(aCategory);
		}
		
		thePost.add("categories", categoriesArray);
		
		
		JsonArray deletedArray = new JsonArray();
		for(String s: MainActivity.deletedContacts)
		{
			JsonObject aContact = new JsonObject();
			aContact.addProperty("name", s);
			deletedArray.add(aContact);
		}
		
		thePost.add("deleted_contacts", deletedArray);
		
		String returnThis = "";
		try
		{
			JsonObject json = thePost;
			
			HttpParams httpParams = new BasicHttpParams();
			HttpConnectionParams.setConnectionTimeout(httpParams,
					TIMEOUT_MILLISEC);
			HttpConnectionParams.setSoTimeout(httpParams, TIMEOUT_MILLISEC);
			HttpClient client = new DefaultHttpClient(httpParams);
			//String url = "http://10.0.2.2:8080/sample1/webservice2.php?json={\"UserName\":1,\"FullName\":2}";
			String url = "http://softeng.cs.uwosh.edu/students/kiserj66/Web/upload_contacts.php";
			HttpPost request = new HttpPost(url);
			request.setEntity(new ByteArrayEntity(json.toString().getBytes(
					"UTF8")));
			request.setHeader("json", json.toString());
			HttpResponse response = client.execute(request);
			HttpEntity entity = response.getEntity();
			// If the response does not enclose an entity, there is no need
			if (entity != null) {
				InputStream instream = entity.getContent();
				String result = RestClient.convertStreamToString(instream);
				Log.i("Read from server", result);
				returnThis = result;
			}
		}
		catch (Throwable t)
		{
			Log.i("Request failed", t.toString());
			returnThis = "Request failed" + t.toString();
		}
		return returnThis;
	}
	
	
	@Override
	protected void onPostExecute(Object result)
	{
		if (MainActivity.db.getUserId() != 0)
		{
			System.out.println(result);
			JsonObject appData = (JsonObject) new JsonParser().parse((String) result);
			SqlConnect db = MainActivity.db;
			db.dropTables();

			populateContactsTable(appData);
			MainActivity.deletedContacts.clear();
			populateCategoriesTable(appData);
			try {
				new GetAllCategoryNamesTask().execute().get();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ExecutionException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			new GetAllContactTask().execute();
		}
	}



	private void populateContactsTable(JsonObject jObj)
	{
		JsonElement jEl = jObj.get("contacts");
		JsonArray jAr = jEl.getAsJsonArray();
		SqlConnect db = MainActivity.db;
		for (int i = 0; i < jAr.size(); i++)
		{
			JsonObject jObj2 = (JsonObject) jAr.get(i);
			db.createContact(
					new Contact(
							jObj2.get("name").getAsString(),
							jObj2.get("address").getAsString(),
							jObj2.get("cell_number").getAsString(),
							jObj2.get("alt_number").getAsString(),
							jObj2.get("email").getAsString(),
							jObj2.get("comments").getAsString(),
							Integer.parseInt(jObj2.get("category").getAsString()),
							jObj2.get("ts").getAsString()
							)
					);
		}
		db.close();
	}
	
	private void populateCategoriesTable(JsonObject jObj)
	{
		JsonElement jEl = jObj.get("categories");
		JsonArray jAr = jEl.getAsJsonArray();
		SqlConnect db = MainActivity.db;
		for (int i = 0; i < jAr.size(); i++)
		{
			JsonObject jObj2 = (JsonObject) jAr.get(i);
			db.createCategory(
					new Category(
							Integer.parseInt(jObj2.get("cid").getAsString()),
							jObj2.get("category_name").getAsString(),
							jObj2.get("ts").getAsString()
							)
					);
		}
		db.close();
	}
	
}
